

import { isNull } from "../Define";
import { IValue } from "../data/IValue";
import { IMap } from "../data/IMap";

export default class LocalMap<T = any> implements IMap<T> {

    protected value: IValue<{ [key: string]: T }>;
    protected count: number = 0;

    constructor(value: IValue<{ [key: string]: T }>) {
        this.value = value
    }

    getValue() {
        return this.value.getValue();
    }

    setValue(v: { [key: string]: T }, isSave: boolean = true) {
        this.value.setValue(v, isSave)
    }

    save() {
        this.value.save();
    }

    size() {
        return this.count;
    }

    get(key: any): T {
        let map = this.getValue();
        let data = map[key];
        return data;
    }

    has(key: any): boolean {
        let map = this.getValue();
        return !isNull(map[key])
    }

    set(key: any, data: T, isSave: boolean = true, isReplace: boolean = false) {
        let map = this.getValue();
        if (!map[key]) {
            this.count++;
        }
        map[key] = data
        if (isSave) {
            this.save();
        }

    }


    remove(key: any): void {
        let map = this.getValue();
        if (map[key]) {
            this.count--;
            delete map[key]
            this.save();
        }

    }

    clear(): void {
        this.value.clear()
    }

    hasData() {
        return this.value.hasData();
    }
}
